package com.sinszm.mdb.condition;

import com.sinszm.common.exception.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.StringUtils;

import static com.sinszm.mdb.exception.MdbError.MDB_ERROR_001;

/**
 * 数据连接池参数配置条件触发器
 *
 * @author chenjianbo
 */
public class MdbCondition extends SpringBootCondition {

    private static final String MDB_PLATFORM = "spring.datasource.platform";
    private static final String MDB_DRIVER_CLASS = "spring.datasource.driver-class-name";
    private static final String MDB_URL = "spring.datasource.url";

    private static final Logger logger = LoggerFactory.getLogger(MdbCondition.class);

    @Override
    public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
        String platform = context.getEnvironment().getProperty(MDB_PLATFORM, String.class);
        String driverClass = context.getEnvironment().getProperty(MDB_DRIVER_CLASS, String.class);
        String url = context.getEnvironment().getProperty(MDB_URL, String.class);
        if (StringUtils.isEmpty(platform)
                || StringUtils.isEmpty(driverClass)
                || StringUtils.isEmpty(url)) {
            logger.error("platform = {}, driverClass = {}, url = {}", platform, driverClass, url);
            throw new ApiException(MDB_ERROR_001);
        }
        return new ConditionOutcome(true, "@Mdb");
    }

}
